package com.shujia.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;

public class MysqlTool {

    private static Connection conn;
    private MysqlTool(){}

    public static Connection getConnection(){
        try {
            //读取配置文件，获取driver,url,username,password
            //创建配置文件对象
            Properties prop = new Properties();
            //加载配置文件
            prop.load(new BufferedReader(new FileReader("mysql-jdbc/src/main/resources/mysqinfo.properties")));
            //根据key获取value值
            String driver = prop.getProperty("driver");
            String url = prop.getProperty("url");
            String username = prop.getProperty("username");
            String password = prop.getProperty("password");

            //1、加载驱动
            Class.forName(driver);

            //2、创建与数据库之间的连接
            conn = DriverManager.getConnection(url, username, password);
        }catch (Exception e){
            e.printStackTrace();
        }

        return conn;
    }

    public static void printResultSet(ResultSet resultSet){
        try {
            while (resultSet.next()) {
                int columnCount = resultSet.getMetaData().getColumnCount();
//                int i = 1;
                StringBuilder sb = new StringBuilder();
                for(int i=1;i<=columnCount;i++){
                    sb.append(resultSet.getString(i)).append("\t");
                }
//                while (true){
//                    try {
//                        sb.append(resultSet.getString(i)).append("\t");
//                    }catch (Exception e){
//                        break;
//                    }
//                    i++;
//                }
                System.out.println(sb);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
